import { loginUrl, wxBindAccountUrl, serveUrl } from '../../api/index'
import { userStatusUrl, entryFullUrl } from '../../api/individual'
import { post, individualEntry, getQueryString, previewDocument } from '../../utils/index'

Page({
  data: {
    code: '',
    isRead: false,
    tenantId: '000000',
    userType: 'individual',
    isEntry: true,
    hasConfirmId: false
  },
  getPhoneNumber ({ detail }) { // 获取手机号授权微信登录
    if (detail.errMsg.includes('fail')) {
      wx.navigateBack({})
      return
    }
    const { encryptedData: decryptData, iv } = detail
    wx.checkSession({
      success: () => {
        this.wxLogin(decryptData, iv)
      },
      fail: () => {
        this.getWxCode(() => {
          this.wxLogin(decryptData, iv)
        })
      }
    })
  },
  async wxLogin (decryptData, iv) { // 微信手机授权登录
    const { userType, code, tenantId, hasConfirmId } = this.data
    const { data } = await post(wxBindAccountUrl, { code, decryptData, iv, hasConfirmId })
    if (!data.openid) {
      wx.navigateTo({ url: '/pages/login/login' })
      return
    }
    const loginForm = { grant_type: 'custom_wx', tenantId, wx_code: data.openid }
    const userInfo = await post(loginUrl, loginForm, { 'Tenant-Id': tenantId, 'User-Type': userType, 'System-type': 'dispatch' }, false)
    this.saveInfo(userInfo)
  },
  async saveInfo (userInfo) { // 保存用户信息，并做跳转操作
    const { userType } = this.data
    wx.setStorageSync('user', userInfo)
    wx.setStorageSync('token', userInfo.access_token)
    // if (userType === 'individual') {
    //   const { data } = await post(userStatusUrl)
    //   individualEntry(data)
    //   return
    // }
    wx.navigateTo({ url: '/pages/hr/hr' })
  },
  getWxCode (callback) { // 提前wx.login获取code，避免解密失败
    wx.login({
      success: res => {
        const { code } = res
        this.data.code = code
        callback && callback()
      }
    })
  },
  onChange ({ detail }) { // 同意条款
    this.setData({ isRead: detail })
  },
  handleRead () { // 阅读条款
    previewDocument(serveUrl)
  },
  getQuery (q) { // 扫码后获取参数
    const url = decodeURIComponent(q)
    const companyId = getQueryString(url, 'companyId')
    const confirmId = getQueryString(url, 'confirmId')
    wx.setStorageSync('companyId', companyId)
    wx.setStorageSync('confirmId', confirmId)
    this.data.hasConfirmId = true
    this.entryFull(confirmId)
  },
  async entryFull (confirmId) { // 判断企业派遣确认表人数是否已满
    const { data } = await post(entryFullUrl, { confirmId }, {}, false)
    if (typeof data === 'boolean') {
      this.setData({ isEntry: false })
      wx.showToast({ title: '入职人数已满，请联系人事', icon: 'none' })
    }
  },
  onLoad ({ q }) {
    if (q) {
      this.getQuery(q)
    }
  },
  onShow () {
    this.getWxCode()
  }
})